﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Complex
{
    class Complex
    {
        private double real = 0;
        private double imaginery = 0;

        public Complex(double real, double imaginery)
        {
            this.real = real;
            this.imaginery = imaginery;
        }

        public static Complex operator !(Complex number)
        {
            Complex result = new Complex(number.real, -number.imaginery);
            return result;
        }

        public static Complex operator +(Complex number1, Complex number2)
        {
            Complex result = new Complex(number1.real + number2.real, number1.imaginery + number2.imaginery);
            return result;
        }

        public static Complex operator -(Complex number1, Complex number2)
        {
            Complex result = new Complex(number1.real - number2.real, number1.imaginery - number2.imaginery);
            return result;
        }

        public static Complex operator *(Complex number1, Complex number2)
        {
            double newReal = number1.real * number2.real - number1.imaginery * number2.imaginery;
            double newImaginery = number1.real * number2.imaginery - number1.imaginery * number2.real;
            Complex result = new Complex(newReal, newImaginery);
            return result;
        }

        public static Complex operator /(Complex number1, Complex number2)
        {
            double newReal = (number1.real * number2.real + number1.imaginery * number2.imaginery) / 
                (number1.real * number1.real + number2.real * number2.real);
            double newImaginery = (number1.imaginery * number2.real - number1.real * number2.imaginery) /
                (number1.real * number1.real + number2.real * number2.real);
            Complex result = new Complex(newReal, newImaginery);
            return result;
        }

        public static explicit operator double(Complex number)
        {
            return number.real;
        }

        public static implicit operator Complex(double number)
        {
            Complex result = new Complex(number, 0);
            return result;
        }

        public override string ToString()
        {
            string complexNumber = String.Format("({0}) + ({1})*i", this.real, this.imaginery);
            return complexNumber;
        }

        public double this[int index]
        {
            get
            {
                if (index == 0)
                {
                    return this.real;
                }
                else if (index == 1)
                {
                    return this.imaginery;
                }
                else
                {
                    throw new IndexOutOfRangeException();
                }
            }
        }
    }
}
